package com.wuye.controller;

import com.wuye.model.*;
import com.wuye.repository.MenuActivityRepository;
import com.wuye.repository.MenuRepository;
import com.wuye.repository.OrderItemRepository;
import com.wuye.repository.OrderRepository;
import com.wuye.service.MenuService;
import com.wuye.service.OrderService;
import com.wuye.web.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhanchi on 2016/6/8.
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private SessionHandler sessionHandler;
    @Autowired
    private MenuRepository menuRepository;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private OrderItemRepository orderItemRepository;
    @Autowired
    private MenuService menuService;
    @Autowired
    private MenuActivityRepository menuActivity;

    private Log log = LogFactory.getLog(this.getClass());
    @RequestMapping("/orderList.jspa")
    public String orderList(HttpSession session) {
        UserSession userSession = sessionHandler.getUserSession(session);
        List<OrderDetail> orderDetails = orderService.findAllOrderList(userSession.getUserId());
        JSONObject json = ST.ok.getJsonObject();
        json.put("orders",orderDetails);
        return json.toString();
    }

    //取消订单操作
    @RequestMapping("/cancelOrder.jspa")
    public String cancelOrder(HttpSession session, @RequestParam("orderSn") String orderSn) {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat formt  =   new SimpleDateFormat("HH:mm:ss");
        c  =  Calendar.getInstance(Locale.CHINESE);
        String currenttime= formt.format(c.getTime());
        Long dates = null;
        Long dates1 = null;
        JSONObject result = new JSONObject();
        try {
            dates = formt.parse(currenttime).getTime();
            dates1 = formt.parse("16:30:00").getTime();
            if(dates<=dates1) {
                Order o = orderRepository.findByOrderNum(orderSn);
                if (null == o) {
                    return ST.dataNotExists.toJson();
                }
                if(o.getPayMethod().equalsIgnoreCase("WEIXIN")) o.setOrderState(OrderState.FOR_REFUND.toString());
                else o.setOrderState(OrderState.CANCEL.toString());
                List<OrderItem> myList = orderItemRepository.findByOrderSn(orderSn);
                for(OrderItem item : myList){
                    int aa = item.getAmount();
                    MenuActivity ma = menuActivity.findOne(item.getMenuId());
                    ma.setStoreNum(ma.getStoreNum()+aa);
                    menuActivity.save(ma);
                }
                orderRepository.save(o);
                return ST.ok.toJson();
            }
        }catch(Exception e){
            e.getMessage();
        }
        return ST.cannotCancle.toJson();
    }
    @RequestMapping("/orderDetail.jspa")
    public OrderDetail orderDetail(HttpSession session, @RequestParam("orderSn") String orderSn) {
        Order o = orderRepository.findByOrderNum(orderSn);
        /*if(null == o){
            return ST.dataNotExists.toString();
        }*/
        OrderDetail od = new OrderDetail(o);
        List<OrderItem> orderItems = orderItemRepository.findByOrderSn(orderSn);
        od.setOrderItems(orderItems);
        JSONObject json = ST.ok.getJsonObject();
        json.put("order",od);
        return od;
    }
    //加入购物车操作
    @RequestMapping("/addToCart.jspa")
    public String addToCart(HttpSession session, @RequestParam("select") String select) {
        String psp[] = select.split(",");
        //订单项编号+@@+订单项数量
        List<ShoppingCartItem> menus = new ArrayList<ShoppingCartItem>();
        UserSession userSession = sessionHandler.getUserSession(session);
        for (String p : psp) {
            String nn[] = p.split("@@");
            if (nn.length == 2 && LangUtil.isNum(nn[1])) {
                String menuId = nn[0];
                Integer menuNum = new Integer(nn[1]);
                MenuActivity ma = menuActivity.findByMenuId(nn[0]);
                log.info(ma.getStoreNum());
                int nums = 0;
                if(ma.getStoreNum()==null){
                    nums = 0;
                }else{
                    nums = ma.getStoreNum();
                }
                int nm = Integer.valueOf(nn[1]);
                if(nums>=nm) {
                    if (menuNum == 0) {
                        continue;
                    } else {
                        Menu m = menuRepository.findOne(menuId);
                        ShoppingCartItem i = new ShoppingCartItem();
                        i.setMenuId(menuId);
                        i.setItemName(m.getItemName());
                        i.setNum(menuNum);
                        i.setAmount(menuNum * m.getItemPrice());
                        i.setItemPrice(m.getItemPrice());
                        menus.add(i);
                    }
                }else{
                    return ST.goodsCannotSale.toJson();
                }
            }
        }
        userSession.setShoppingCart(menus);
        return ST.ok.toJson();
    }

    @RequestMapping("/cartInfo.jspa")
    public String cartInfo(HttpSession session) {
        UserSession userSession = sessionHandler.getUserSession(session);
        JSONObject json = ST.ok.getJsonObject();
        json.put("menus", userSession.getShoppingCart());
        json.put("amount", userSession.getTotalPrice());
        if (userSession.getTotalPrice() > 0) {
            return json.toString();
        } else {
            return ST.dataNotExists.toJson();
        }
    }

    @RequestMapping("/orderMenus.jspa")
    public String orderMenus(HttpSession session) {
        UserSession userSession = sessionHandler.getUserSession(session);
        JSONObject json = ST.ok.getJsonObject();
        json.put("menus", userSession.getShoppingCart());
        json.put("amount", userSession.getTotalPrice());
        return json.toString();
    }

    @RequestMapping("/submitOrder.jspa")
    public String submitOrder(HttpSession session, @RequestParam("payMethod") String payMethod, @RequestParam("memo") String memo) {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat formt  =   new SimpleDateFormat("HH:mm:ss");
        c  =  Calendar.getInstance(Locale.CHINESE);
        String currenttime= formt.format(c.getTime());
        Long dates = null;
        Long dates1 = null;
        Long dates2 = null;
        JSONObject result = new JSONObject();
        try {
            dates = formt.parse(currenttime).getTime();
            JSONObject str = menuService.orderTimes();
            String s1 = (String)str.get("s1");
            String s2 = (String)str.get("s2");
            dates1 = formt.parse(s1).getTime();
            dates2 = formt.parse(s2).getTime();
            if(dates>=dates1 && dates<=dates2) {
                UserSession userSession = sessionHandler.getUserSession(session);
                List<ShoppingCartItem> cartItems = userSession.getShoppingCart();
                for(ShoppingCartItem shops : cartItems){
                    MenuActivity ma = menuActivity.findOne(shops.getMenuId());
                    int nums = 0;
                    if(ma.getStoreNum()==null){
                        nums = 0;
                    }else{
                        nums = ma.getStoreNum();
                    }
                    if(nums<shops.getNum()){
                        return ST.goodsCannotSale.toJson();
                    }
                    int am = shops.getNum();
                    ma.setStoreNum(nums-am);
                    menuActivity.save(ma);
                }
                String userName = userSession.getUserName(), cellPhone = userSession.getCellPhone(), userId = userSession.getUserId();
                result = orderService.createOrder(userId, cellPhone, userName, payMethod, userSession.getTotalPrice(), cartItems, memo);
                if (result.getInt("code") == 0) {
                    userSession.setShoppingCart(new ArrayList<ShoppingCartItem>());
                }
                return result.toString();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return ST.cannotOrder.toJson();
    }


}
